package com.atguigu.gmall.search.lister;

import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.pms.entity.*;
import com.atguigu.gmall.search.feign.GmallPmsClient;
import com.atguigu.gmall.search.feign.GmallWmsClient;
import com.atguigu.gmall.search.pojo.Goods;
import com.atguigu.gmall.search.pojo.SearchAttrValueVo;
import com.atguigu.gmall.search.repository.GoodsRepository;
import com.atguigu.gmall.wms.entity.WareSkuEntity;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class SearchLister {

    @Autowired
    GmallPmsClient gmallPmsApi;

    @Autowired
    GmallWmsClient gmallWmsApi;

    @Autowired
    GoodsRepository goodsRepository;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue("SEARCH_INSERT_QUEUE"),
            exchange = @Exchange(value = "PMS_SPU_EXCHANGE",ignoreDeclarationExceptions = "true",type = ExchangeTypes.TOPIC),
            key = {"item.insert", "item.update"}
    ))
    public void message(Long spuId, Message message, Channel channel) throws IOException {
        if (spuId==null){
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException e) {
                //拒收 是否放回队列
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
                e.printStackTrace();
            }
        }
        //根据spu查询商品信息
        ResponseVo<SpuEntity> spuEntityResponseVo = gmallPmsApi.querySpuById(spuId);
        SpuEntity spuEntity = spuEntityResponseVo.getData();
        if (spuEntity==null){
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            return;
        }
        //查询sku信息
        ResponseVo<List<SkuEntity>> responseVo = gmallPmsApi.querySkusBySpuId(spuEntity.getId());
        List<SkuEntity> skus = responseVo.getData();
        try {
            if (!CollectionUtils.isEmpty(skus)){
                //遍历每一个sku
                List<Goods> goodsList = skus.stream().map(sku -> {
                    Goods goods = new Goods();
                    goods.setSkuId(sku.getId());
                    goods.setPrice(sku.getPrice());
                    goods.setDefaultImage(sku.getDefaultImage());
                    goods.setTitle(sku.getTitle());
                    goods.setSubtitle(sku.getSubtitle());
                    goods.setCreateTime(spuEntity.getCreateTime());
                    //查询库存信息
                    ResponseVo<List<WareSkuEntity>> listResponseVo = gmallWmsApi.queryWareSkusBySkuId(sku.getId());
                    List<WareSkuEntity> wareSkuEntities = listResponseVo.getData();
                    if (!CollectionUtils.isEmpty(wareSkuEntities)){
    //                        long asLong = wareSkuEntities.stream().mapToLong(item -> {
    //                            Long sales = item.getSales();
    //                            return sales;
    //                        }).reduce((a, b) -> {
    //                            return a + b;
    //                        }).getAsLong();
                        goods.setSales(wareSkuEntities.stream().mapToLong(WareSkuEntity::getSales).reduce((a,b)->a+b).getAsLong());
                        //anyMatch任意一个元素成功 返回true
                        goods.setStore(wareSkuEntities.stream().anyMatch(wareSkuEntity -> wareSkuEntity.getStock()- wareSkuEntity.getStockLocked()>0));
                    }
                    //查询品牌信息
                    ResponseVo<BrandEntity> brandEntityResponseVo = gmallPmsApi.queryBrandById(sku.getBrandId());
                    BrandEntity brandEntity = brandEntityResponseVo.getData();
                    if(brandEntity!=null){
                        goods.setLogo(brandEntity.getLogo());
                        goods.setBrandId(brandEntity.getId());
                        goods.setBrandName(brandEntity.getName());
                    }
                    //查询分类
                    ResponseVo<CategoryEntity> entityResponseVo = gmallPmsApi.queryCategoryById(sku.getCategoryId());
                    CategoryEntity categoryEntity= entityResponseVo.getData();
                    if(categoryEntity!=null){
                        goods.setCategoryId(categoryEntity.getId());
                        goods.setCategoryName(categoryEntity.getName());
                    }
                    //查询销售参数信息
                    ResponseVo<List<SkuAttrValueEntity>> searchAttrValueByCidAndSkuId = gmallPmsApi.querySearchAttrValueByCidAndSkuId(sku.getCategoryId(), sku.getId());
                    List<SkuAttrValueEntity> skuAttrValueEntities = searchAttrValueByCidAndSkuId.getData();
                    List<SearchAttrValueVo> searchAttrValueVos = new ArrayList<>();
                    if (!CollectionUtils.isEmpty(skuAttrValueEntities)){
                        searchAttrValueVos.addAll(skuAttrValueEntities.stream().map(item->{
                            SearchAttrValueVo searchAttrValueVo = new SearchAttrValueVo();
                            BeanUtils.copyProperties(item,searchAttrValueVo);
                            return searchAttrValueVo;
                        }).collect(Collectors.toList()));
                    }
                    //查询基本规格参数信息
                    ResponseVo<List<SpuAttrValueEntity>> querySearchAttrValueByCidAndSpuId = gmallPmsApi.querySearchAttrValueByCidAndSpuId(sku.getCategoryId(), spuEntity.getId());
                    List<SpuAttrValueEntity> spuAttrValueEntities = querySearchAttrValueByCidAndSpuId.getData();
                    if (!CollectionUtils.isEmpty(spuAttrValueEntities)){
                        searchAttrValueVos.addAll(spuAttrValueEntities.stream().map(item->{
                            SearchAttrValueVo searchAttrValueVo = new SearchAttrValueVo();
                            BeanUtils.copyProperties(item,searchAttrValueVo);
                            return searchAttrValueVo;
                        }).collect(Collectors.toList()));
                    }
                    goods.setSearchAttrs(searchAttrValueVos);
                    return goods;
                }).collect(Collectors.toList());
                goodsRepository.saveAll(goodsList);
            }
            //false 不指定批量消费
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            //判断是否重新投递了一次
            if (message.getMessageProperties().getRedelivered()){
                channel.basicReject(message.getMessageProperties().getDeliveryTag(),false);
            }
            channel.basicNack(message.getMessageProperties().getDeliveryTag(),false,true);
        }


    }
}
